<template>
	<view class="my-login">
		<van-cell-group>
			<van-field center clearable label="用户名" placeholder="请输入用户名" :value="username" @change="changeUsername">
			</van-field>
			<van-field center clearable label="密码" placeholder="请输入密码" type="password" :value="password"
				@change="changePassword">
			</van-field>
			<view style="padding: 32rpx; box-sizing: border-box;">
				<van-button round type="info" block @click="toLogin">
					登录
				</van-button>
			</view>
		</van-cell-group>
	</view>
</template>

<script>
	import {
		login
	} from '@/request/api.js'

	export default {
		data() {
			return {
				username: '',
				password: ''
			};
		},
		onLoad() {
			try {
				const value = uni.getStorageSync('userLocal');
				const {
					username,
					password
				} = JSON.parse(uni.getStorageSync('userLocal'))
				this.username = username
				this.password = password
			} catch (e) {
				// error
			}
		},
		methods: {
			toLogin() {
				if (this.username.length === 0 || this.password.length === 0) {
					uni.showToast({
						icon: 'none',
						title: '请输入用户名和密码'
					})
					return
				}
				login({
					Account: this.username,
					Password: this.password
				}).then(res => {
					console.log(res)
					if (res.code === 200) {
						uni.setStorage({
							// 保存账号密码
							key: 'userLocal',
							data: JSON.stringify({
								username: this.username,
								password: this.password
							}),
							success: () => {
								uni.setStorage({
									// 保存用户信息
									key: 'userInfo',
									data: res.result,
									success: () => {
										uni.redirectTo({
											url: '../safe_data_pages/safe_data_pages'
										})
									}
								})
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.message
						})
					}
				}).catch(e => {
					console.log(e)
					uni.showToast({
						icon: 'none',
						title: '登录失败'
					})
				})
			},
			changeUsername(e) {
				this.username = e.detail
			},
			changePassword(e) {
				this.password = e.detail
			}
		}
	}
</script>

<style lang="scss">
	.my-login {
		background-color: #F8F8F8;
		height: 100vh;
	}
</style>
